package crontab

import (
	"fmt"
	global2 "longmen/server/config/global"
	imsdk2 "longmen/server/internal/rpc/tencentim/imsdk"
	"longmen/server/internal/services/consumers/publisher"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/mysql/models/models_sports"
	"time"

	"github.com/spf13/cast"
)

// 刪除 關注已開賽賽事tag
func DeleteTagsByStarted() {
	global2.Log.Info("DeleteTagsByStarted start")
	return
	matchUsers := getYesterdayMatch()

	// 移除tag
	if len(matchUsers) > 0 {
		for matchId, users := range matchUsers {
			// 每次api最多100個user tag
			times := len(users) / 100
			if len(users)%100 != 0 {
				times++
			}
			var totalUser int
			for i := 0; i < times; i++ {
				var tagUsers []string
				for j := i * 100; j < (i+1)*100 && j < len(users); j++ {
					tagUsers = append(tagUsers, users[j])
					totalUser++
				}
				imsdk2.GetSdk().DeleteTags(tagUsers, []string{fmt.Sprintf("%d", matchId)})
			}
			global2.Log.Info("delete tag == matchId : ", matchId, " total users : ", totalUser)
		}
	}
	global2.Log.Info("DeleteTagsByStarted end")
}

func getYesterdayMatch() map[int][]string {
	t := time.Now()
	today := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()).Unix()

	y := time.Now().AddDate(0, 0, -1)
	yesterday := time.Date(y.Year(), y.Month(), y.Day(), 0, 0, 0, 0, t.Location()).Unix()

	// 取出昨日開賽的賽事以及關注用戶
	o := make([]*models_sports.MatchFavorite, 0)
	err := global2.Sport().Raw(fmt.Sprintf("select match_id , user_id from db_match_favorite where match_id in ( select match_id from db_matches_schedule where match_time >= %v and match_time < %v ) ", yesterday, today)).
		Find(&o).
		Error
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert2(), err.Error())
	}

	var m = make(map[int][]string)
	for _, v := range o {
		m[v.MatchId] = append(m[v.MatchId], cast.ToString(v.UserId))
	}
	return m
}

// 發送後台消息
func SendBackofficeMsg() {
	global2.Log.Info("SendBackofficeMsg start")
	// 查表：待發送 + 預設時間已到
	var msgs []*models_main.OfflineMsg
	var err error
	msgs, err = waitingSendMsg()
	if err != nil {
		global2.Log.Errorf("GetOfflineMsg error: %s", err.Error())
		return
	}

	// 發送消息
	if len(msgs) > 0 {
		for n, _ := range msgs {
			// 發送消息
			global2.Log.Infof("SendBackoffice:%+v", msgs[n])
			err = sendMsg(msgs[n])
			if err != nil {
				global2.Log.Errorf("sendMsg error: %s", err.Error())
				msgs[n].PushStatus = 3
				global2.Log.Info("SendBackofficeMsg fail ID : ", msgs[n].ID)
				continue
			} else {
				msgs[n].PushStatus = 2
				global2.Log.Info("SendBackofficeMsg success ID : ", msgs[n].ID)
			}
		} //end for
		global2.Log.Info("SendBackoffice: finish")
		err = db_main.UpdateOfflineMsg(msgs)
		if err != nil {
			global2.Log.Errorf("UpdateOfflineMsg error: %s", err.Error())
		}
	} //endif
	global2.Log.Info("SendBackofficeMsg end")
}

func sendMsg(msg *models_main.OfflineMsg) error {

	arg := imsdk2.OfflineArgs{
		RoomType:  int32(msg.JumpType),
		SportType: int32(msg.SportId),
		RoomId:    int32(msg.MatchId),
	}

	s := imsdk2.OfflineMsgNats{
		OfflineArgs: arg,
		Condition:   imsdk2.Condition{},
		User:        msg.User,
		Title:       msg.Title,
		Content:     msg.Content,
	}
	err := global2.PublisherTxChat.BroadCast(publisher.AllMemberPush, s)
	if err != nil {
		global2.Log.Errorf("NATS PublishAsync SendOfflineMsg error: %s", err.Error())
		return err
	}

	return nil
}

func waitingSendMsg() ([]*models_main.OfflineMsg, error) {
	msgs, err := db_main.GetBackofficeToSend()
	if err != nil {
		return nil, err
	}
	global2.Log.Info("offline msg waiting Send lens: ", len(msgs))
	return msgs, nil
}

// 發送15 分鐘後開賽的消息
func SendMatchStartMsg() {
	global2.Log.Info("SendMatchStartMsg start")

	// 查詢15分鐘後開賽的賽事 額外加上5秒，避免後台發送的消息時間重疊
	var matches []models_sports.MatchTempSchedule
	err := global2.Sport().Where("match_time >= ? and match_time < ?", time.Now().Unix()+905, time.Now().Unix()+965).Find(&matches).Error
	if err != nil {
		global2.Log.Errorf("GetMatchStart error: %s", err.Error())
		return
	}

	// 發送消息
	if len(matches) > 0 {
		for _, match := range matches {
			// 發送消息
			err = sendMatchStartMsg(match)
			if err != nil {
				global2.Log.Errorf("sendMatchStartMsg error: %s", err.Error())
				continue
			} else {
				global2.Log.Info("SendMatchStartMsg success ID : ", match.MatchId)
			}
		}
	}

	global2.Log.Info("SendMatchStartMsg end")
}

func sendMatchStartMsg(match models_sports.MatchTempSchedule) error {
	arg := imsdk2.OfflineArgs{
		RoomType:  1,
		SportType: int32(match.SportId),
		RoomId:    int32(match.MatchId),
	}

	condition := imsdk2.Condition{
		TagsAnd: []string{fmt.Sprintf("match_%d", match.MatchId), imsdk2.NOTIFY_START_MATCH},
	}

	c := imsdk2.OfflineMsgNats{
		OfflineArgs: arg,
		Condition:   condition,
		User:        nil,
		Title:       "赛事提醒",
		Content:     fmt.Sprintf("您关注的 %s vs %s 马上开始了，点击观看", match.Home, match.Away),
	}

	err := global2.PublisherTxChat.BroadCast(publisher.AllMemberPush, c)
	if err != nil {
		global2.Log.Errorf("NATS PublishAsync SendOfflineMsg error: %s", err.Error())
		return err
	}

	return nil
}
